package channel

import (
	"context"
	schema "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/tenant/channel"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"github.com/zeromicro/go-zero/core/logc"
	"gorm.io/gorm"
)

type TenantChannelQrBankModel struct {
	ctx context.Context
	db  *gorm.DB
}

func NewTenantChannelQrBankModel(ctx context.Context, db *gorm.DB) *TenantChannelQrBankModel {
	return &TenantChannelQrBankModel{
		ctx: ctx,
		db:  db,
	}
}

func (model *TenantChannelQrBankModel) getDb() *gorm.DB {
	if model.db != nil {
		return model.db
	}
	return svc.Db
}

func (model *TenantChannelQrBankModel) CreateQrBank(qrBank *schema.TenantChannelQrBank) error {
	res := model.getDb().Create(qrBank)
	if err := res.Error; err != nil {
		logc.Error(model.ctx, "tenantChannel-CreateQrBank,err", err)
		return err
	}
	return nil
}

func (model *TenantChannelQrBankModel) GetQrBankById(id int64) (*schema.TenantChannelQrBank, error) {
	var qrBank schema.TenantChannelQrBank
	res := model.getDb().First(&qrBank, id)
	if err := res.Error; err != nil {
		logc.Error(model.ctx, "tenantChannel-GetQrBankById,err", err)
		return nil, err
	}
	return &qrBank, nil
}

func (model *TenantChannelQrBankModel) GetAllQrBank(bankName string) ([]schema.TenantChannelQrBank, error) {
	var qrBanks []schema.TenantChannelQrBank
	query := model.getDb().Model(&schema.TenantChannelQrBank{})

	if bankName != "" {
		query = query.Where("bank_name LIKE ?", "%"+bankName+"%")
	}

	res := query.Find(&qrBanks)
	if err := res.Error; err != nil {
		logc.Error(model.ctx, "tenantChannel-GetAllQrBank,err", err)
		return nil, err
	}
	return qrBanks, nil
}

func (model *TenantChannelQrBankModel) UpdateQrBank(id int64, updates map[string]interface{}) error {
	res := model.getDb().Model(&schema.TenantChannelQrBank{}).Where("id = ?", id).Updates(updates)
	if err := res.Error; err != nil {
		logc.Error(model.ctx, "tenantChannel-UpdateQrBank,err", err)
		return err
	}
	return nil
}

func (model *TenantChannelQrBankModel) DeleteQrBank(id int64) error {
	res := model.getDb().Where("id = ?", id).Delete(&schema.TenantChannelQrBank{})
	if err := res.Error; err != nil {
		logc.Error(model.ctx, "tenantChannel-DeleteQrBank,err", err)
		return err
	}
	return nil
}
